let express = require("express");
const fs = require('fs');
const path = require("path");
let app = express();
let persons=fs.readFileSync(__dirname+"/persons.json")
persons=JSON.parse(persons)

app.use(express.urlencoded({extends:false}))

app.get("/login", (req, res) => {
    let data = fs.readFileSync(__dirname + "/login.html")
    res.end(data)
})

app.post("/logins", (req, res) => {
    persons.find(v => v.username == req.body.username && v.password == req.body.password) ?
    res.send("登录成功") :
    res.send("登录失败")
})

app.get("/reg", (req, res) => {
    let data = fs.readFileSync(__dirname + "/register.html")
    res.end(data)
})

app.post("/regs", (req, res) => {
    let flag = persons.findIndex(v => v.username == req.body.username)
    if (flag == -1) {
        res.send("可以注册")
        persons.push(req.body)
        let data=JSON.stringify(persons)
        fs.writeFileSync(__dirname+"/persons.json",data)
    }else{
        res.send('用户名已经被占用')
    }
})


app.listen(3000, "127.0.0.1", () => {
    console.log("启动成功");
})